package com.zt.weibo.main;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.Weibo;
import com.zt.weibo.R;
import com.zt.weibo.WeiboApp;
import com.zt.weibo.interfaces.IWeiboPopListener;
import com.zt.weibo.interfaces.IWeiboServiceListener;
import com.zt.weibo.utils.ExitTimer;
import com.zt.weibo.utils.JsonAnalyze;
import com.zt.weibo.utils.PrintLog;
import com.zt.weibo.utils.SwitchActivity;
import com.zt.weibo.vo.StatusInfo;

public class WeiboActivity extends Activity {
    private ImageButton mNewWeiboBtn = null;
    private ImageButton mRefreshBtn = null;
	private ListView mResultList = null;
    private JsonAnalyze mJsonAnalyze = null;
    private StatusAdapter mAdapter = null;
    private ArrayList<StatusInfo> mInfos = null;
    private ProgressDialog mWaitDialog = null;
    private WeiboSendPopwin mSentPopwin = null;
    private WeiboMenuPopwin mMenuPopwin = null;
    private RefreshListener refreshListener = null;
    private int iCurPosInList = 0;
    private int iFocusPosInList = -1;
    private boolean bIsIniting = false;
    private boolean bIsWantNewer = false;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.weibo_main);
		PrintLog.debug("WeiboActivity On Create");
		WeiboApp.addActivity(this);
		if (null != savedInstanceState)
		{
			PrintLog.debug("Read Data On SavedInstanceState");
			WeiboApp.mWeibo.setupConsumerConfig(savedInstanceState.getString("APP_KEY"), 
					savedInstanceState.getString("APP_SECRET"));
			WeiboApp.mWeibo.setRedirectUrl(savedInstanceState.getString("URL_REDIRECT"));
			WeiboApp.mWeibo.setAccessToken((AccessToken) savedInstanceState.getSerializable("ACCESS_TOKEN"));
		}
		findView();
		initView();
		setListeners();
	}
    
	@Override
	protected void onStart()
	{
		super.onStart();
		PrintLog.debug("WeiboActivity On Start");
	}

  	@Override
	protected void onNewIntent(Intent intent)
	{
		super.onNewIntent(intent);
		PrintLog.debug("WeiboActivity On NewIntent");
		setIntent(intent);
		bIsIniting = true;
		mResultList.setAdapter(null);
		WeiboApp.mServer.getStatus(0 + "", refreshListener, true);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		PrintLog.debug("WeiboActivity On Resume");
		PrintLog.debug("intent = " + getIntent().getAction());
		if(-1 != iFocusPosInList)
		{
			mResultList.setSelection(iFocusPosInList);
			iFocusPosInList = -1;
		}
		else
		{
			mResultList.setSelection(iCurPosInList);
		}
	}  

	@Override
	protected void onPause()
	{
		super.onPause();
		PrintLog.debug("WeiboActivity On Pause");
		getIntent().setAction("");
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		PrintLog.debug("WeiboActivity On Stop");
		PrintLog.debug("Now Position is = " + mResultList.getFirstVisiblePosition());
		iCurPosInList = mResultList.getFirstVisiblePosition();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		PrintLog.debug("WeiboActivity On Destroy");
		WeiboApp.delActivity(this);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		PrintLog.debug("On SavedInstanceState");
		outState.putString("APP_KEY", Weibo.getAppKey());
		outState.putString("APP_SECRET", Weibo.getAppSecret());
		outState.putString("URL_REDIRECT", WeiboApp.mWeibo.getRedirectUrl());
		outState.putSerializable("ACCESS_TOKEN", WeiboApp.mWeibo.getAccessToken());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.add(0, 0, 0, "账号管理").setIcon(R.drawable.ic_menu_allfriends);
		menu.add(0, 1, 1, "退出").setIcon(R.drawable.ic_menu_exit);
		menu.add(0, 2, 2, "关于").setIcon(R.drawable.ic_menu_info_details);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case 0:
			SwitchActivity.login(WeiboActivity.this);
			break;
		case 1:
			SwitchActivity.exit(WeiboActivity.this);
			break;
		case 2:
			AboutPopwin aboutPopwin = new AboutPopwin(WeiboActivity.this, getLayoutInflater().
					inflate(R.layout.weibo_main, null));
			aboutPopwin.show();
			break;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			if(!ExitTimer.isExit)
			{
				ExitTimer.isExit = true;
				Toast.makeText(WeiboActivity.this, getString(R.string.toast_exit_app), 1500).show();
				if(!ExitTimer.hasTask)
				{
					ExitTimer.m_ExitTimer.schedule(ExitTimer.m_ExitTask, 1500, 1500);
				}
			}
			else
			{
				SwitchActivity.exit(WeiboActivity.this);
				return true;
			}
		}
		return false;
	}

	/**
	 * 刷新微博（20条）。开始刷新时显示进度条，刷新完毕取消进度条并且刷新列表。
	 * @param bIsWantNewer 新微博：true，旧微博：false
	 */
	private void refreshStatus(boolean bIsWantNewer)
	{
		String strId = "";
		this.bIsWantNewer = bIsWantNewer;
		if(bIsWantNewer)
		{
			strId = mAdapter.getItem(0).strId;
		}
		else
		{
			strId = mAdapter.getItem(mAdapter.getCount() - 1).strId;
		}
		WeiboApp.mServer.getStatus(strId, refreshListener, bIsWantNewer);
	}
	
	private void findView()
	{
        mResultList = (ListView) findViewById(R.id.status_list);
        mNewWeiboBtn = (ImageButton) findViewById(R.id.weibo_main_send_btn);
        mRefreshBtn = (ImageButton) findViewById(R.id.weibo_main_refresh_btn);
	}
	
	private void initView()
	{
		bIsIniting = true;
		mJsonAnalyze = JsonAnalyze.getInstance();
		mWaitDialog = new ProgressDialog(WeiboActivity.this);
		mWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mWaitDialog.setMessage(getString(R.string.progress_dialog_loading));
		mAdapter = new StatusAdapter(WeiboActivity.this);
		refreshListener = new RefreshListener();
		WeiboApp.mServer.getStatus(0 + "", refreshListener, true);
	}
	
	private void setListeners()
	{
		ButtonListener buttonListener = new ButtonListener();
		ItemClickListener itemClickListener = new ItemClickListener();
		ItemLongClickListener longClickListener = new ItemLongClickListener();
		ScrollListener scrollListener = new ScrollListener();
		
		mResultList.setOnItemClickListener(itemClickListener);
		mResultList.setOnItemLongClickListener(longClickListener);
		mResultList.setOnScrollListener(scrollListener);
        mNewWeiboBtn.setOnClickListener(buttonListener);
        mRefreshBtn.setOnClickListener(buttonListener);
	}
	
	private class RefreshListener implements IWeiboServiceListener
	{
		@Override
		public void onStart()
		{
			try
			{
				mWaitDialog.show();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

		@SuppressWarnings("unchecked")
		@Override
		//如果没出错，进度框还在，消隐之；解析JSON生成微博列表，如果是初始化阶段，则重新设置微博显示并完成初始化
		//如果不是初始化阶段，则更新微博显示，根据获取新旧微博来不同方式刷新页面。
		public void onCompl(String strJson)
		{
			try
			{
				if (mWaitDialog.isShowing())
				{
					mWaitDialog.dismiss();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			mInfos = (ArrayList<StatusInfo>)mJsonAnalyze.getInfoListFromJson(strJson);
			if (null == mInfos)
			{
				return;
			}
			if (bIsIniting)
			{
				mAdapter.setStatusList(mInfos);
				mResultList.setAdapter(mAdapter);
				bIsIniting = false;
			}
			else
			{
				mAdapter.updateStatusList(mInfos, bIsWantNewer);
				if(bIsWantNewer)
				{
					mResultList.requestFocus();
					mResultList.setSelectionAfterHeaderView(); 
				}
			}
			mAdapter.notifyDataSetChanged();
		}

		@Override
		public void onError(String str)
		{
			StringBuffer strBuffer = new StringBuffer();
			strBuffer.append(str.substring(8, str.length()));
			PrintLog.debug(strBuffer.toString());
			int iErrorCode = Integer.parseInt(strBuffer.toString());
			switch(iErrorCode)
			{
			case 21327://token过期，跳转至登陆界面重新授权
				Toast.makeText(WeiboActivity.this, getString(R.string.toast_token_invaled), 1000).show();
				WeiboApp.mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run()
					{
						SwitchActivity.login(WeiboActivity.this);
						finish();
					}
				}, 1200);
				break;
			}
		}
	}

	private class ButtonListener implements OnClickListener
	{
		@Override
		public void onClick(View v)
		{
			switch (v.getId())
			{
			case R.id.weibo_main_send_btn:
				mSentPopwin = new WeiboSendPopwin(WeiboActivity.this, 
						getLayoutInflater().inflate(R.layout.weibo_main, null), new IWeiboPopListener() {
							
							@Override
							public void onPopShow()
							{
								
							}
							
							@Override
							public void onPopDismiss()
							{
								refreshStatus(true);
							}
						});
				mSentPopwin.show();
				break;
			case R.id.weibo_main_refresh_btn:
				bIsIniting = true;
				WeiboApp.mServer.getStatus(0 + "", refreshListener, true);
				break;
			}
		}
	}

	private class ItemClickListener implements OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			System.out.println(arg0.getItemAtPosition(arg2).toString());
			iFocusPosInList = arg2;
			SwitchActivity.weiboDetail(WeiboActivity.this, (StatusInfo) arg0.getItemAtPosition(arg2));
		}
	}

	private class ItemLongClickListener implements OnItemLongClickListener
	{
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id)
		{
    		mMenuPopwin = new WeiboMenuPopwin(WeiboActivity.this, 
    				getLayoutInflater().inflate(R.layout.weibo_main, null), new IWeiboPopListener() {
						
						@Override
						public void onPopShow()
						{
							
						}
						
						@Override
						public void onPopDismiss()
						{
							refreshStatus(true);
						}
					});
    		mMenuPopwin.show((StatusInfo) arg0.getItemAtPosition(position));
			return false;
		}
	}
	
	private class ScrollListener implements OnScrollListener
	{
		boolean bIsLast = false;
		boolean bIsFirst = false;
		boolean bIsScrolling = false;
		boolean bIsScrollEnd = false;
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{
			if(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState)
			{
				bIsScrolling = false;
			}
			else
			{
				if(!bIsScrolling && OnScrollListener.SCROLL_STATE_FLING == scrollState)
				{
					bIsScrollEnd = true;
					bIsScrolling = false;
					if(bIsScrollEnd && bIsFirst)
					{
						refreshStatus(true);
						bIsFirst = false;
					}
					if(bIsScrollEnd && bIsLast)
					{
						refreshStatus(false);
						bIsLast = false;
					}
				}
			}
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
				int totalItemCount)
		{
			bIsScrolling = true;
			if(0 == firstVisibleItem && totalItemCount > 0)
			{
				bIsFirst = true;
			}
			else
			{
				bIsFirst = false;
			}
			if(firstVisibleItem + visibleItemCount >= totalItemCount && totalItemCount > 0)
			{
				bIsLast = true;
			}
			else
			{
				bIsLast = false;
			}
		}
	}
	
}
